<template>
  <q-form ref="loginForm" @keyup.enter="submitForm" class="column">
    <a-q-input outlined v-model="单项.user_name" placeholder="请输入 用户名 或 手机号" dense clearable :rules="rules.user_name">
      <template v-slot:prepend>
        <q-icon name="person" />
      </template>
    </a-q-input>
    <a-q-input v-model="单项.password" outlined :type="isPwd ? 'password' : 'text'" placeholder="请输入密码" dense
      :rules="rules.password" clearable>
      <template v-slot:prepend>
        <q-icon name="lock_open" />
      </template>
      <template v-slot:append>
        <q-icon :name="isPwd ? 'visibility_off' : 'visibility'" class="cursor-pointer" @click="isPwd = !isPwd" />
      </template>
    </a-q-input>
    <a-q-input outlined dense v-model.trim="单项.captcha" placeholder="请输入验证码" clearable :rules="rules.captcha">
      <template v-slot:prepend>
        <q-icon name="security" />
      </template>
      <template v-slot:after>
        <q-btn padding="none" style="width: 120px; height: 100%" @click="loginVerify">
          <q-img :src="picPath" />
        </q-btn>
      </template>
    </a-q-input>
    <q-btn class="" color="primary" icon="login" label="登录" @click="submitForm" />
    <!-- <q-btn class="q-mt-md" color="primary" icon="restart_alt" label="初始化系统" @click="checkInit" /> -->
  </q-form>
</template>

<script setup lang="ts">
// @ts-nocheck==
const 同意 = ref(false)
const password = ref('')
const isPwd = ref(true)

import { captcha } from 'amtf/api/user'

import { onMounted, reactive, ref } from 'vue'
import { useUserStore } from '@/stores/use_user_store'

// 获取验证码
const loginVerify = async () => {
  const ele =await captcha()
  picPath.value = ele.data.picPath
  单项.captchaId = ele.data.captchaId
  单项.openCaptcha = ele.data.openCaptcha
}
onMounted(() => {
  // getCaptcha()
  loginVerify()
})

// 登录相关操作
const loginForm = ref(null)
const picPath = ref('')
const 单项 = reactive({
  user_name: 'admin',
  password: '',
  captcha: '',
  captchaId: '',
  openCaptcha: false,
})
const rules = reactive({
  user_name: [(val) => (val && val.length > 0) || '请输入用户名或者手机号'],
  password: [(val) => (val && val.length > 0) || '请输入密码'],
  captcha: [(val) => (val && val.length > 0) || '请输入验证码'],
})

const userStore = useUserStore()
const login = async () => {
  return await userStore.LoginIn(单项)
}

import * as util from "amtf/utils"

const submitForm = () => {
  console.log(`登录 👉`)
  loginForm.value.validate().then(async (success) => {
    if (success) {
      // 通过验证，请求登陆
      const flag = await login()
      // 登陆失败，刷新验证码
      if (!flag) {
        await loginVerify()
        return false
      }
      // 登陆成功
      return true
    }
    else {
      util.提示(util.提示enum.出错, '内容不符合要求 ')
      // await loginVerify()
      return false
    }
  })
}

</script>

<style scoped lang="scss">
@use "./login.scss";
</style>
